package ca.etsmtl.log660.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.hibernate.Session;

import ca.etsmtl.log660.configuration.SessionFactoryHelper;
import ca.etsmtl.log660.entity.model.Utilisateurs;

/**
 * Servlet implementation class ConnexionServlet
 */
@WebServlet("/ConnexionServlet")
public class ConnexionServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ConnexionServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession(true);
        PrintWriter out = response.getWriter();
        
        String user = request.getParameter("j_username");
        String password = request.getParameter("j_password");;
        
        Session uneSession = SessionFactoryHelper.getSessionFactory().openSession();
    	
		uneSession.beginTransaction();
		List<Utilisateurs> lesUtilisateurs = uneSession.createQuery("FROM Utilisateurs u WHERE u.courriel = '"+user.replace("'","''")+"' and u.motdepasse = '"+password.replace("'","''")+"' ").list();

		if(lesUtilisateurs.size() == 1){
			Utilisateurs unClient = lesUtilisateurs.get(0);
			
			out.println("Bonjour " + unClient.getNom());
			session.setAttribute("clientConnect",unClient);
			request.getRequestDispatcher("pages/accueil.jsp").forward(request, response);
		}else{
			request.getRequestDispatcher("logonerror.jsp").forward(request, response);
		}
		
		uneSession.close();
		
	}

}
